package com.qf.intercetor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.qf.Constant.AuthConstant;
import com.qf.Constant.OrderConstant;
import com.qf.entity.User;
import com.qf.util.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/22/17:55
 * @Description: 动态数据源拦截器
 */
@Component
@Slf4j
public class DynamicDataSource implements HandlerInterceptor {
    public Integer getTabIndex(){
        return tabInexThreadLocak.get();
    }

    private ThreadLocal<Integer> tabInexThreadLocak = new ThreadLocal<>();
    @Autowired
    private OrderUtil orderUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute(AuthConstant.AUTH_SESSION);
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/orderController/updateOrderStatus/**", requestURI);
        boolean match1 = antPathMatcher.match("/orderController/getInfoByOid/**", requestURI);

        if (match) {
            return true;
        }
        if (match1) {
            return true;
        }

        if (user==null) {
            response.sendRedirect("http://localhost/auth/login.html");
        }
        String s = orderUtil.lasteUserId(user.getId());
        int uid = Integer.parseInt(s);
        int dbIndex=(uid%OrderConstant.ORDER_DB_SIZE)+1;
        DynamicDataSourceContextHolder.push(OrderConstant.ORDER_DB_PRE+dbIndex);
        //计算订单表的编号
        Integer tabIndex=(uid/OrderConstant.ORDER_DB_SIZE%OrderConstant.ORDER_TABLE_SIZE)+1;
        log.debug("数据库编号"+OrderConstant.ORDER_DB_PRE+dbIndex);
        log.debug("表编号:"+tabIndex);
        tabInexThreadLocak.set(tabIndex);
       //放行
        return true;
    }
}
